// --------------------- 8. R-T Scatter Plot ----------------------- //
inline void a(vector<TH1 *> &v, TH1 *h){ v.push_back((TH1 *)h); }

void chi2(){
  TFile *f = new TFile(getenv("TMP1"));
  TTree *etf = (TTree *)f->Get("etf");
  vector<TH1 *> v;
  TH1 *h0;
  char zcut[64] = "";
  static const int Z = 29;
  if(Z > 0) sprintf(zcut, "az0>%.2f && az0<%.2f", Z-0.5, Z+0.5);

  const char ud[2] = {'U', 'D'}, xy[2] = {'X', 'Y'};
  char hname[64]{}, ly[64]{};
  for(int i = 0; i < 2; i++){ // loop over U, D
    for(int j = 0; j < 2; j++){ // loop over 1, 2
      for(int k = 0; k < 2; k++){ // loop over X, Y
        for(int l = 0; l < 2; l++){ // loop over X1,2
          sprintf(ly, "dcTa%c%d%c%d", ud[i], j, xy[k], l);
          sprintf(hname, "h%s", ly);
          if(0 == i) h0 = new TH2F(hname, Form("chi of %s", ly), 500, -50, 200., 500, -2.5, 2.5);
          else h0 = new TH2F(hname, Form("chi of %s", ly), 500, -100., 400., 500, -5., 5.);
          h0->GetXaxis()->SetTitle("drift time [ns]");
          h0->GetYaxis()->SetTitle("tracking residue [mm]");
          string cut = Form("%s && %s.fired()>=2", zcut, ly); // 2: normal trking; 3: global trking
          etf->Project(hname, Form("%s.GetChi():%s.GetT()", ly, ly), cut.data());
          a(v, h0);
          cout << "Processing " << ly << ": " << zcut << "...\r" << flush;
        } // end for over X1,2
      } // end for over X, Y
    } // end for over 1, 2
  } // end for over U, D
  cout << endl;

  TCanvas *c = new TCanvas("c", "Tracking chi v.s. Drift Time of dcTas", 1680, 1050);
  // c->Divide(4, 4);
  // for(int i = 0; i < 16; i++){ c->cd(i+1); v[i]->Draw("colz"); }
  
  c->Divide(2, 2);
  c->Print("chi2.pdf[");
  for(int i = 0; i < 16; i++){
    c->cd(i%4 + 1);
    v[i]->Draw("colz");
    if((i+1)%4 == 0) c->Print("chi2.pdf");
  } // end for over i
  c->Print("chi2.pdf]");
} // end main function
